Page({
  data: {
    statusText: '准备开始面试',
    currentQuestion: '请介绍一下你自己，并说明为什么适合这个职位？',
    isRecording: false,
    recordDuration: 0,
    isUploading: false,
    showResult: false,
    aiResult: '',
    recordingTimer: null,
    interviewId: '',
    questionId: 'q1'
  },

  onLoad: function(options) {
    // 从URL参数获取面试ID
    if (options.interviewId) {
      this.setData({ interviewId: options.interviewId });
    } else {
      // 测试用：如果没有面试ID，创建一个新面试
      this.createNewInterview();
    }
  },

  createNewInterview: function() {
    // 模拟创建新面试，实际应调用后端API
    wx.request({
      url: 'http://localhost:8080/api/interview/create',
      method: 'POST',
      data: {
        userId: 'user123', // 实际应从登录状态获取
        positionId: 'pos456'
      },
      success: (res) => {
        if (res.statusCode === 201) {
          this.setData({ interviewId: res.data.id });
        }
      }
    });
  },

  toggleRecord: function() {
    const that = this;
    if (!this.data.isRecording) {
      // 开始录音
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.record']) {
            wx.authorize({
              scope: 'scope.record',
              success: () => that.startRecording(),
              fail: () => {
                wx.showToast({ title: '需要录音权限', icon: 'none' });
              }
            });
          } else {
            that.startRecording();
          }
        }
      });
    } else {
      // 停止录音
      this.stopRecording();
    }
  },

  startRecording: function() {
    const that = this;
    this.setData({
      isRecording: true,
      recordDuration: 0,
      statusText: '正在录音...',
      showResult: false
    });

    // 开始计时
    this.data.recordingTimer = setInterval(() => {
      const duration = that.data.recordDuration + 1;
      // 限制录音时长为60秒
      if (duration >= 60) {
        that.stopRecording();
        wx.showToast({ title: '已达最大录音时长', icon: 'none' });
      } else {
        that.setData({ recordDuration: duration });
      }
    }, 1000);

    // 开始录音
    wx.startRecord({
      success: (res) => {
        const tempFilePath = res.tempFilePath;
        that.uploadAudio(tempFilePath);
      },
      fail: (err) => {
        clearInterval(that.data.recordingTimer);
        that.setData({
          isRecording: false,
          statusText: '录音失败，请重试'
        });
        console.error('录音失败:', err);
      }
    });
  },

  stopRecording: function() {
    wx.stopRecord();
    clearInterval(this.data.recordingTimer);
    this.setData({
      isRecording: false,
      statusText: '录音已完成，正在处理...',
      isUploading: true
    });
  },

  uploadAudio: function(tempFilePath) {
    const that = this;
    wx.uploadFile({
      url: `http://localhost:8080/api/interview/${this.data.interviewId}/submit-audio`,
      filePath: tempFilePath,
      name: 'audio',
      formData: {
        questionId: this.data.questionId
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const result = JSON.parse(res.data);
          that.setData({
            showResult: true,
            aiResult: result.result,
            statusText: '面试完成',
            isUploading: false
          });
        } else {
          const error = JSON.parse(res.data);
          wx.showToast({ title: `处理失败: ${error.error}`, icon: 'none' });
          that.setData({ statusText: '处理失败', isUploading: false });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '上传失败，请重试', icon: 'none' });
        that.setData({ statusText: '上传失败', isUploading: false });
        console.error('上传失败:', err);
      }
    });
  },

  formatTime: function(seconds) {
    const minute = Math.floor(seconds / 60);
    const second = seconds % 60;
    return `${minute.toString().padStart(2, '0')}:${second.toString().padStart(2, '0')}`;
  }
})
